package com.graduate.front.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.graduate.common.entity.Result;
import com.graduate.common.entity.Users;
import com.graduate.front.pojo.MyUser;
import org.assertj.core.internal.cglib.asm.$AnnotationVisitor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author bwzfy
 * @create 2021/5/12
 **/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    // 普通会员升级vip的方法
    @ResponseBody
    @GetMapping("/vip")
    public Result<String> upGraduate(HttpSession session) {
        // 进入到数据库中把用户信息状态修改成vip会员
        Users users = (Users) session.getAttribute("user");
        // 将用户状态修改为vip用户
        // 从数据库中根据用户id查询出用户对象
        Users user = usersService.getById(users.getId());
        user.setRole(1);
        usersService.updateById(user);
        // 把session中的用户信息也随之修改
        session.setAttribute("user", user);
        return new Result<String>().success();
    }

    @ResponseBody
    @PostMapping("/register")
    public Result<String> register(@RequestBody Users users) {
        // 通过此方法注册的用户为管理员权限
        users.setRole(0);
        boolean save = usersService.save(users);
        if (save) {
            return new Result<String>().success();
        }else {
            return new Result<String>().failure();
        }
    }

    @ResponseBody
    @PostMapping("/update/password")
    public Result<String> updatePassword(@RequestParam("oldPassword") String oldPassword,
                                         @RequestParam("newPassword") String newPassword,
                                         HttpSession session) {
        MyUser user = (MyUser) session.getAttribute("user");
        Users tempUser = usersService.getById(user.getId());
        if (!oldPassword.equals(tempUser.getPassword())) {
            return new Result<String>().failure();
        }
        UpdateWrapper<Users> wrapper = new UpdateWrapper<>();
        wrapper.set("password", newPassword);
        wrapper.eq("id", user.getId());
        boolean update = usersService.update(wrapper);
        if (update) {
            return new Result<String>().success();
        }else {
            return new Result<String>().failure();
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/userLogin";
    }
}
